package com.haiheng.voiceandbook.voice


import android.content.Intent
import android.graphics.Bitmap
import android.text.TextUtils
import android.util.Log
import android.util.LogPrinter
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View.OnTouchListener
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.AbsListView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.haiheng.bookmusic.base.BaseActivity
import com.haiheng.bookmusic.common.PlayBean
import com.haiheng.bookmusic.utils.GlideUtils
import com.haiheng.voiceandbook.Constants
import com.haiheng.voiceandbook.Constants.Companion.AlbumPage_URL
import com.haiheng.voiceandbook.R
import com.haiheng.voiceandbook.adapter.TrackAdapter
import com.haiheng.voiceandbook.databinding.ActivityTracksBinding
import com.haiheng.voiceandbook.helper.WeakDataHolder
import com.haiheng.voiceandbook.treeview.interfaces.OnScrollToListener
import com.haiheng.voiceandbook.utils.DisplayUtil
import com.haiheng.voiceandbook.utils.ToolUtil
import com.haiheng.voiceandbook.utils.ZXingUtils
import com.tencent.bugly.crashreport.CrashReport
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack
import com.ximalaya.ting.android.opensdk.model.album.Album
import com.ximalaya.ting.android.opensdk.model.track.Track
import com.ximalaya.ting.android.opensdk.model.track.TrackList


/**
 * 标签列表
 */
class TracksActivity : BaseActivity() {
    var activityTracksBinding: ActivityTracksBinding? = null
    private var adapter: TrackAdapter? = null

    var pageNo: Int = 1
    val pageSize: Int = 100
    val album: Album? = null

    //查询ACS平台书的清单
    private var list: ArrayList<Track> = java.util.ArrayList()

    //var url = "https://yidu.seaeverit.com/webview/index.html#/pages/albumPage/albumPage"

    override fun initData() {
        showLoadingDialog()
        getTracks()
        //拿到专辑数据
        val data = intent.getBundleExtra("bundle")
        val album = data?.getParcelable<Album>("album")
        activityTracksBinding?.tvTitle?.setText(album?.albumTitle)
        if (TextUtils.isEmpty(album?.albumIntro)) {
            activityTracksBinding?.tvContent?.setText("暂无介绍")
        } else {
            activityTracksBinding?.tvContent?.setText(album?.albumIntro)
        }

        activityTracksBinding?.tvCount?.setText(ToolUtil.getFormatNumber(album?.playCount))

        GlideUtils.load(this, album!!.coverUrlLarge, activityTracksBinding?.ivHead!!)

        if (TextUtils.isEmpty(album.albumScore)) {
            activityTracksBinding?.tvScore?.setText("暂无评分")
        } else {
            activityTracksBinding?.tvScore?.setText(album.albumScore)
        }
        if (TextUtils.isEmpty(album.recommendReason)) {
            activityTracksBinding?.tvContentTitle?.setText("暂无推荐描述")
        } else {
            activityTracksBinding?.tvContentTitle?.setText(album.recommendReason)
        }

        if (album.announcer == null) {
            activityTracksBinding?.tvName?.setText("暂无作者")
        } else {
            activityTracksBinding?.tvName?.setText(album.announcer.nickname)
            GlideUtils.load(this, album.announcer.avatarUrl, activityTracksBinding?.ivUserHead!!)
        }
       val  url ="${AlbumPage_URL}?id=${album.id}&libraryNo=${Constants.getLibraryCode()}&PhysicalAddress=${Constants.getDevicesId()}"





        Log.e(TAG, "url: $url")
        val bitmap: Bitmap = ZXingUtils.createQRImage(
            url,
            DisplayUtil.dip2px(this, 84f),
            DisplayUtil.dip2px(this, 84f)
        )
        activityTracksBinding?.ivQcode?.setImageBitmap(bitmap)

        if (album != null && album.id.toString().isNotBlank()){
            reportClick(album.id.toString())
        }


    }


    /**
     *  查询热门数据
     */
    private fun getTracks() {
        val map = HashMap<String, String>()
        //专辑ID
        map.put(DTransferConstants.ALBUM_ID, intent.getStringExtra("id")!!)
        ////sort String 否 "asc"表示喜马拉雅正序，"desc"表示喜马拉雅倒序，
        // "time_asc"表示时间升序，"time_desc"表示时间降序，默认为"asc"
        map.put(DTransferConstants.SORT, "asc")

        //返回第几页，必须大于等于1，不填默认为1
        map.put(DTransferConstants.PAGE, pageNo.toString())
        //每页多少条，默认20，最多不超过200
        map.put(DTransferConstants.PAGE_SIZE, pageSize.toString())
        CommonRequest.getTracks(map, object : IDataCallBack<TrackList> {

            override fun onError(p0: Int, p1: String?) {
                hideLoadingDialog()
                adapter?.loadMoreFail()
                Log.e("dddd","=======加载完成onError======:"+adapter?.isLoading+p1);
                activityTracksBinding?.srHasData?.finishRefresh()
                activityTracksBinding?.srHasData?.finishLoadMore()
                if (pageNo > 1) {
                    pageNo--
                }
                Toast.makeText(this@TracksActivity, "系统异常：${p1}", Toast.LENGTH_SHORT).show()

            }

            override fun onSuccess(p0: TrackList?) {
                hideLoadingDialog()
                adapter?.loadMoreComplete()
                Log.i("dddd","=======加载完成onSuccess======:"+adapter?.isLoading);
                activityTracksBinding?.srHasData?.finishRefresh()
                activityTracksBinding?.srHasData?.finishLoadMore()
                if (p0 != null && p0.tracks != null && p0.tracks.size > 0) {
                    activityTracksBinding?.tvTotalCount?.setText("总共${p0.totalCount}条记录")
                    if (pageNo == 1) {
                        list.clear()
                    }
                    list.addAll(p0!!.tracks)
                    adapter?.notifyDataSetChanged()
                } else {
                    if (pageNo > 1) {
                        pageNo--
                    }
                }

            }
        })
    }

    var height = 0
    override fun initView() {


        val layoutManager: LinearLayoutManager = object : LinearLayoutManager(this) {
            override fun canScrollVertically(): Boolean {
                return true
            }
        }
        activityTracksBinding?.recyclerView?.layoutManager = layoutManager

        adapter = TrackAdapter(R.layout.item_hot_track, list)
        activityTracksBinding?.recyclerView?.adapter = adapter
        initPlayer()


        //布局的状态发生变化或者可见性发生变化才会调用
        activityTracksBinding?.recyclerView?.getViewTreeObserver()
            ?.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    //处理完后remove掉，至于为什么，后面有解释
                    activityTracksBinding?.recyclerView?.getViewTreeObserver()
                        ?.removeOnGlobalLayoutListener(this)
                    height = activityTracksBinding?.recyclerView?.measuredHeight!!
                }
            })

    }

    override fun intiLayout() {
        activityTracksBinding = ActivityTracksBinding.inflate(LayoutInflater.from(this))
        setContentView(activityTracksBinding?.getRoot())
    }

    /**
     * 初始化播放器
     */
    private fun initPlayer() {


    }


    override fun onDestroy() {
        super.onDestroy()
        CommonRequest.release()
    }

    override fun initDataChange() {
    }

    override fun initListener() {

        activityTracksBinding?.ivBack?.setOnClickListener {
            finish()
        }
        activityTracksBinding?.srHasData?.setOnRefreshListener {
            pageNo = 1
            getTracks()
        }

        activityTracksBinding?.srHasData?.setOnLoadMoreListener {
            pageNo++
            getTracks()
        }
        val mOnScrollListener: RecyclerView.OnScrollListener =
            object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {

                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState ==RecyclerView.SCROLL_STATE_IDLE){
                        //暂停
                        Log.i("dddd","======暂停======");
                    }
                    if (newState==RecyclerView.SCROLL_STATE_DRAGGING){
                        //滑动
                        Log.i("dddd","=======正在滑动======");
                    }

                }
            }
        activityTracksBinding?.recyclerView?.addOnScrollListener(mOnScrollListener)
        adapter?.apply {
            openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
            setOnItemClickListener { adapter, view, position ->
                Log.i("dddd","======点击===== ："+RecyclerView.SCROLL_STATE_IDLE+"_isloading；"+adapter.isLoading);
                var listAdapter = adapter.data;
                val bean = PlayBean(listAdapter as ArrayList<Track>, position)
                val bundle = intent.getBundleExtra("bundle")
//                    bundle?.putParcelable("bean", bean)
                WeakDataHolder.getInstance().saveData("bean",bean)
                val intent = Intent(this@TracksActivity, PlayerActivity::class.java)
                intent.putExtra("bundle", bundle)
//                val currentBean = MyApplication.getInstance().bean
//                if(bean!=currentBean){
//                    XmPlayerManager.release()
//                }

                startActivity(intent)
            }
            setOnLoadMoreListener({
                setEnableLoadMore(false)
                pageNo++
                getTracks()
            }, activityTracksBinding?.recyclerView)
        }
        var currentY = 0
        activityTracksBinding?.srBottom?.setOnTouchListener(OnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                Log.e(TAG, "down x = ${event.rawX} and y = ${event.rawY}")
                currentY = event.rawY.toInt()
            }
            if (event.action == MotionEvent.ACTION_UP) {
                Log.e(TAG, "up x = ${event.rawX} and y = ${event.rawY}")
                if (activityTracksBinding?.recyclerView?.measuredHeight!! < 500) {
                    height = 25
                } else if (activityTracksBinding?.recyclerView?.measuredHeight!! > 500 && activityTracksBinding?.recyclerView?.measuredHeight!! < 1200) {
                    height = 960
                } else if (activityTracksBinding?.recyclerView?.measuredHeight!! > 1200) {
                    height = 1850
                }
                val params = activityTracksBinding?.recyclerView?.layoutParams
                params?.height = height
                activityTracksBinding?.recyclerView?.layoutParams = params
            }
            if (event.action == MotionEvent.ACTION_MOVE) {
                val moveY = event.rawY.toInt() - currentY
                //移动之后的高
                val afterHeight = height - moveY
                Log.e(
                    TAG,
                    "move x = ${event.rawX} and y = ${event.rawY} and moveY = ${moveY} and height = ${height} and afterHeight = ${afterHeight}"
                )
                if (afterHeight >= 25 && afterHeight < 1920) {
                    val params = activityTracksBinding?.recyclerView?.layoutParams
                    val height = afterHeight
                    params?.height = height
                    activityTracksBinding?.recyclerView?.layoutParams = params
                }
            }
            true

        }
        )


    }


    fun reportClick(albumId:String){
        bookViewModel?.reportAlbumClick(albumId)
    }

}